/*
 * Copyright (c) 2022.版权所有高金磊
 */

package 领扣算法.AA中等题.推多米诺;

import java.util.HashSet;

public class Main {
    public String pushDominoes(String dominoes) {
        byte[] data=new byte[dominoes.length()];
        HashSet<Integer> indexs=new HashSet<>();
        char[] chars=dominoes.toCharArray();
        for (int i = 0; i < data.length; i++) {
            switch (chars[i]){
                case 'L':
                    data[i]=-1;
                    break;
                case 'R':
                    data[i]=1;
                    break;
                default:{
                    indexs.add(i);
                }
            }
        }
        indexs.remove(0);
        indexs.remove(data.length-1);
        HashSet<Integer> middle=new HashSet<>();
        boolean flag=true;
        while (flag){
            flag=false;
            middle.clear();
            for (Integer index : indexs) {
                if (indexs.contains(index-1)&&indexs.contains(index+1))
                    continue;
                if (data[index-1]==-data[index+1]){
                    middle.add(index);
                    continue;
                }
                if (data[index-1]==1){
                    middle.add(index);
                    flag=true;
                    data[index]=1;
                    continue;
                }
                if (data[index+1]==-1){
                    middle.add(index);
                    flag=true;
                    data[index]=-1;
                }
            }
            indexs.removeAll(middle);

        }
        if (data[0]==0&&data[1]==-1)
            data[0]=-1;
        if (data[data.length-1]==0&&data[data.length-2]==1)
            data[data.length-1]=1;
        StringBuilder stringBuilder=new StringBuilder();
        for (byte datum : data) {
            switch (datum){
                case -1:
                    stringBuilder.append('L');
                    break;
                case 1:
                    stringBuilder.append('R');
                    break;
                case 0:
                    stringBuilder.append('.');
            }
        }
        return stringBuilder.toString();
    }
}
